/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: TimedTask
 * Author:   Administrator
 * Date:     2019/6/25 0:15
 * Description: 定时任务
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.sunlord.controller;

import OThinker.Common.Organization.Models.User;
import OThinker.H3.Entity.Instance.Data.IInstanceDataItem;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import OThinker.H3.Entity.Instance.InstanceState;
import OThinker.H3.Entity.Query;
import com.alibaba.druid.sql.visitor.functions.If;
import com.h3bpm.base.util.AppUtility;
import com.sunlord.dto.SunlordResult;
import com.sunlord.service.SunlordService;
import data.DataRowCollection;
import data.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 〈一句话功能简述〉<br> 
 * 〈定时任务〉
 *
 * @author Administrator
 * @create 2019/6/25
 * @since 1.0.0
 */
@Component
public class TimedTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(TimedTask.class);

    @Autowired
    private SunlordService sunlordService;

    /**
     *  客户建档反写
     */
    @Scheduled(cron="0 0/3 * * * ?")
    public void custFanxie() {
        LOGGER.info("定时任务开始...");

        taskBpcMaster();
        taskContactMaster();

        LOGGER.info("定时任务结束...");
    }


    /**
     *  客户档案主数据 contactMaster 任务
     */
    private void taskContactMaster(){


        String sql = "SELECT OBJECTID from I_CONTACTMASTER where CCNCRM is null or  LENGTH(trim(CCNCRM))=0";
        String x3Sql = "select CCNCRM_0,OBJECTID_0,BPCNUM_0 from ZCONTACT where OBJECTID_0 in ( %s) and  (CCNCRM_0 is not null and LENGTH( trim( CCNCRM_0 )) > 0)";
        String updateSql = "UPDATE I_CONTACTMASTER set CCNCRM='%s',BPCNUM='%s' WHERE OBJECTID='%s'";
        try {

            DataRowCollection rows =  AppUtility.getEngine().getQuery().QueryTable(sql).getRows();

            if(rows == null || rows.size()==0){
                LOGGER.info("未查到需要反写的bizObjectId,contactMaster任务结束...");
                return ;
            }

            String[] bizObjectId = new String[rows.size()];

            StringBuilder ids = new StringBuilder();

            for (int i = 0; i < rows.size(); i++) {
                String id = rows.get(i).getString("OBJECTID");
                ids.append("'").append(id).append("'");
                if (i != bizObjectId.length-1){
                    ids.append(",");
                }
            }
            LOGGER.info("taskContactMaster rows.size()="+rows.size());

            x3Sql = String.format(x3Sql,ids.toString());

            SunlordResult sunlordResult = sunlordService.x3fanxie(x3Sql,"OBJECTID_0","CCNCRM_0","BPCNUM_0");

            List<String> updateSqlList = new  ArrayList<>();

            if (sunlordResult != null && sunlordResult.isSuccess()){
                Map<String,List<Object>> map =  (Map<String,List<Object>>)sunlordResult.getData();
                if (map != null && !map.isEmpty()){
                    for (Map.Entry<String,List<Object>> entry :map.entrySet()){
                        if ( entry.getValue() != null && entry.getValue().size()>0 ){
                            updateSqlList.add(String.format(updateSql, entry.getValue().get(0),entry.getValue().get(1), entry.getKey()));
                        }
                    }
                }
            }

            boolean b = sunlordService.ExecuteEngineSql(updateSqlList);

            if (b){
                LOGGER.info("客户档案taskContactMaster 成功...");
            }else {
                LOGGER.info("客户档案taskContactMaster 失败...");
            }

        } catch (Exception e) {
            LOGGER.info("客户档案taskContactMaster任务异常...",e);
        }


    }

    /**
     *  客户档案主数据bpcmaster任务
     */
    private void taskBpcMaster() {
        Query query = AppUtility.getEngine().getQuery();

        String sql = "SELECT xs.OBJECTID,inst.OBJECTID as INSTID,BIZOBJECTSCHEMACODE from OT_INSTANCECONTEXT inst  " +
                "  left join I_BPCMASTER xs  on inst.BIZOBJECTID = xs.OBJECTID and inst.BIZOBJECTSCHEMACODE='BPCMASTER' " +
                "   WHERE  xs.OBJECTID  is not NULL and   inst.STATE = 4 and( xs.BPCNUM is null or LENGTH( trim( xs.BPCNUM ))=0)";

        DataTable dataTable = query.QueryTable(sql);
        DataRowCollection rows = dataTable.getRows();

        try {
            if(rows == null || rows.size()==0){
                LOGGER.info("未查到需要反写的bizObjectId,定时任务结束...");
                return ;
            }
            Map<String,String> instIdMap = new HashMap<>(32);
            String[] bizObjectId = new String[rows.size()];
            for (int i = 0; i < rows.size(); i++) {
                String id = rows.get(i).getString("OBJECTID");
                bizObjectId[i]=id;
                instIdMap.put(id,rows.get(i).getString("INSTID"));
            }
            LOGGER.info("taskBpcMaster bizObjectid[].szie()="+bizObjectId.length+","+ Arrays.toString(bizObjectId));

            String x3Sql = "select BPCNUM_0,OBJECTID_0 from ZBPCUSTOMER where OBJECTID_0 in ( %s) and IMPFLG_0 = 2 and (BPCNUM_0 is not null or LENGTH( trim( BPCNUM_0 )) > 0)";

            StringBuilder ids = new StringBuilder();
            for (int i = 0; i < bizObjectId.length; i++) {
                ids.append("'").append(bizObjectId[i]).append("'");
                if (i != bizObjectId.length-1){
                    ids.append(",");
                }
            }
            x3Sql = String.format(x3Sql,ids.toString());


            SunlordResult sunlordResult = sunlordService.x3fanxie(x3Sql,"OBJECTID_0","BPCNUM_0");

            if (sunlordResult != null && sunlordResult.isSuccess()){
                Map<String,List<Object>> map =  (Map<String,List<Object>>)sunlordResult.getData();

                if (map != null && !map.isEmpty()){
                    for (Map.Entry<String,List<Object>> entry :map.entrySet()){
                        if ( entry.getValue() != null && entry.getValue().size()>0 ){
                            InstanceData instanceData = new InstanceData(AppUtility.getEngine(),instIdMap.get(entry.getKey()) , User.AdministratorID);
                            if (instanceData != null){
                                LOGGER.info("建档反写:"+instanceData.getItem("BPRNAM").getValue()+","+entry.getKey()+","+entry.getValue());
                                IInstanceDataItem item = instanceData.getItem("BPCNUM");
                                item.setValue(entry.getValue().get(0));
                                instanceData.Submit();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.info("客户档案主表任务异常...",e);
        }

    }
}